<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use Laravel\Socialite\Facades\Socialite;

class LoginController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles authenticating users for the application and
    | redirecting them to your home screen. The controller uses a trait
    | to conveniently provide its functionality to your applications.
    |
    */

    use AuthenticatesUsers;

    /**
     * Where to redirect users after login.
     *
     * @var string
     */
    protected $redirectTo = '/';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        //$this->redirectTo = \URL::previous();
        $this->middleware('guest')->except('logout');
    }

    public function oauth(Request $request,$third)
    {
        if($this->checkDriver($third)){
            return Socialite::driver($third)->redirect();
        }else{
            dd("驱动[{$third}]未配置!");
        }
    }

    public function callback(Request $request,$third)
    {
        if($this->checkDriver($third)){
            $oauthUser = Socialite::driver($third)->user();

            $data = [
                'nickname' => $oauthUser->getNickname(),
                'avatar'   => $oauthUser->getAvatar(),
                'open_id'  => $oauthUser->getId(),
                'sex'      => $oauthUser['sex'] == 1 ? '男' : '女',
            ];
            return $data;
        }else{
            dd("驱动[{$third}]未配置!");
        }
    }

    /**
     * 简单检测驱动配置是否存在.
     *
     * @return boolean
     */
    protected function checkDriver($third){
        return config('services.'.$third) ?: false;
    }
}
